package web.servlet.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.User;
import domain.response.LoginResponse;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.LyyGlobal;
import utils.LyyLogUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        UserService service=new UserServiceImpl();
        User user=null;
        Exception exception=null;
        try {
            user = service.login(userName, password);
        } catch (Exception e) {
            exception=e;
            LyyLogUtil.logeE(e.getMessage());
        }
        LoginResponse loginResponse=new LoginResponse();
        if(exception!=null){
            loginResponse.setStatus(0);
            String message = exception.getMessage();
            if("Incorrect result size: expected 1, actual 0".equals(message)){
                loginResponse.setErrMsg("登录失败，用户名或密码错误！");
            }else {
                loginResponse.setErrMsg(message);
            }
        }else {
            request.getSession().setAttribute(LyyGlobal.USER_KEY,user);
            //request.getSession().setMaxInactiveInterval(1);
            LyyLogUtil.logD("将用户对象存入session，"+user);
            loginResponse.setStatus(1);
            loginResponse.setUser(user);
        }
        response.setContentType("application/json;charset=utf-8");
        ObjectMapper mapper=new ObjectMapper();
        mapper.writeValue(response.getOutputStream(),loginResponse);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
